import React, { FC, useState } from 'react'
import { Typography, Empty, Table, Tag, Button, Space, Modal, message, Spin } from 'antd'
import styles from './common.module.scss'
import { useTitle, useRequest } from 'ahooks'
import { ExclamationCircleFilled } from '@ant-design/icons'
// 搜索组件
import ListSearch from '../../components/ListSearch'
// 引入自定义分页组件
import TPageControl from '../../components/TPageControl'

import useLoadQuestionListData from '../../hooks/useLoadQuestionListData'

//引入更新单个试卷的请求
import { updateQuestionListService, deleteQuestionService } from '../../services/question'
const { Title } = Typography

const { confirm } = Modal

const Trash: FC = () => {
  useTitle('湘大问卷-回收站')

  const { data = {}, loading, refresh } = useLoadQuestionListData({ isDelete: true })
  const { list = [], total = 0 } = data

  // 记录选中的id
  const [selectedIds, setSelectedIds] = useState<string[]>([])

  // 恢复
  const { run: recover } = useRequest(
    async () => {
      for await (const id of selectedIds) {
        await updateQuestionListService(id, { isDelete: false })
      }
    },
    {
      manual: true,
      debounceWait: 500, //防抖
      onSuccess() {
        message.success('恢复成功!')
        refresh() //手动刷新列表
        setSelectedIds([]) //重置选择的id列表
      },
    }
  )

  // 删除
  const { run: deleteQuestion } = useRequest(async () => await deleteQuestionService(selectedIds), {
    manual: true,
    onSuccess() {
      message.success('删除成功:')
      refresh() //手动刷新
      setSelectedIds([]) //重置选择的id列表
    },
  })

  const tableColumns = [
    {
      title: '标题',
      dataIndex: 'title',
      // key: 'title',循环列的key,它会默认取dataIndex的值
    },
    {
      title: '是否发布',
      dataIndex: 'isPublished',
      render: (isPublished: boolean) => {
        return isPublished ? <Tag color="processing">已发布</Tag> : <Tag>未发布</Tag>
      },
    },
    {
      title: '答卷数量',
      dataIndex: 'answerCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
  ]

  function del() {
    confirm({
      title: '确定要删除吗?',
      content: '删除后将无法恢复',
      icon: <ExclamationCircleFilled />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteQuestion()
      },
    })
  }

  // 把JSX片段定为变量
  const TableElement = (
    <>
      <div>
        <Space>
          <Button type="primary" disabled={selectedIds.length === 0} onClick={recover}>
            恢复
          </Button>
          <Button danger disabled={selectedIds.length === 0} onClick={del}>
            删除
          </Button>
        </Space>
      </div>

      <Table
        dataSource={list}
        columns={tableColumns}
        pagination={false}
        rowKey={item => item._id}
        rowSelection={{
          type: 'checkbox',
          onChange: selectedRowKeys => {
            //['340000197503201411', '120000198408198430', '23000020010519055X']
            setSelectedIds(selectedRowKeys as string[])
          },
        }}
      />
    </>
  )

  return (
    <>
      <div className={styles.header}>
        <div className={styles.left}>
          <Title level={3}>回收站</Title>
        </div>
        <div className={styles.right}>
          <ListSearch />
        </div>
      </div>
      <div className={styles.container}>
        {loading && (
          <div style={{ textAlign: 'center' }}>
            <Spin />
          </div>
        )}
        {!loading && list.length === 0 && <Empty description="暂无数据" />}
        {list.length > 0 && TableElement}
      </div>
      <div className={styles.footer}>
        <TPageControl total={total} />
      </div>
    </>
  )
}

export default Trash
